package com.wiwf.model.mqtt.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author kehui
 */
@Configuration(proxyBeanMethods = false)
public class SendMqttBackCfg {

    public static final String TOP = "send";

    @Value("${base.mqtt."+TOP+".url}")
    private String url;
    @Value("${base.mqtt."+TOP+".username}")
    private String username;
    @Value("${base.mqtt."+TOP+".password}")
    private String password;
    @Value("${base.mqtt."+TOP+".start-connect}")
    private Boolean startConnect;

    @Value("${base.mqtt."+TOP+".receiver.client}")
    private String clientcId;
    
    @Bean(TOP+"MqttConnectOptions")
    public MqttConnectOptions getSenderMqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();

        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        options.setConnectionTimeout(100);
        options.setKeepAliveInterval(30);
        return options;
    }

    @Bean(TOP+"MqttClient")
    public MqttClient getMqttClient(@Autowired @Qualifier(TOP+"MqttConnectOptions") MqttConnectOptions options) throws MqttException {
    	MqttClient client = new MqttClient(url, clientcId, new MemoryPersistence()); 
    	if(startConnect) {
    		client.connect(options);
    	}
        return client;
    }
}
